<template>
	<!-- 图片预览区 -->
	<section class="section">
		<div class="preview">
			<img @click="fileUpload" :src="result.dataURL" />
		</div>
	</section>

    <!-- 选择图片 -->   
	<section class="section">
		<div class="select">
            <el-button class="selectBtn" type="primary" size="large" @click="fileUpload">更换头像</el-button>
			<input class="selectImg" ref="uploadInput" type="file" accept="image/jpg, image/jpeg, image/png, image/gif" @change="selectFile" />
		</div>
		<!-- 设置一个按钮 -->
		<!-- 设置一个按钮 -->
	</section>

	<!-- 用于裁切的弹窗 -->
	<Modal v-model:visible="isShowDialog" title="图片裁切" :maskClosable="false">
		<template #footer>
			<Button @click="isShowDialog = false">取消</Button>
			<Button @click="reset">重置</Button>
			<Button type="primary" @click="getResult">裁切</Button>
		</template>

		<!-- 图片裁切插件 -->
		<VuePictureCropper :boxStyle="{
        width: '100%',
        height: '100%',
        backgroundColor: '#f8f8f8',
        margin: 'auto',
      }" :img="pic" :options="{
        viewMode: 1,
        dragMode: 'move',
        aspectRatio: 1,
        cropBoxResizable: false,
      }" :presetMode="{
        mode:'round',
        width: 100,
        height: 100,
      }" />
		<!-- 图片裁切插件 -->
	</Modal>
	<!-- 用于裁切的弹窗 -->
</template>

<script lang="ts">
import request from '../api/request'
import { inject, reactive, ref } from "vue";
import { Button, Modal } from "ant-design-vue";
import { UploadOutlined } from "@ant-design/icons-vue";
import VuePictureCropper, { cropper } from "vue-picture-cropper";
import { ElMessage } from 'element-plus';
interface Result {
	dataURL: string;
}
export default {
	components: {
		Button,
		Modal,
		VuePictureCropper,
		UploadOutlined,
	},
	setup(props , {emit}) {
        const result: Result = reactive({
			dataURL: '',  
		});
        // 获取用户头像
		const getUserInfo = () => {
			request.get('/userMain').then((res) => {
				// 头像不为空，则获取头像
				if (res.data.picture) {
					result.dataURL = res.data.picture
                    console.log(typeof res.data.picture)
                    console.log('pic' , res.data.picture)
				} else {
					result.dataURL = '../../public/img/defaultPicture.png'
				}
			})
		}
		getUserInfo()
		const uploadInput = ref<HTMLInputElement | null>(null);
		const pic = ref<string>("");
		
        console.log(result)
		const isShowDialog = ref<boolean>(false);
		/**
		 * 选择图片
		 */
		const selectFile = (e: Event): void => {
			// 如果有多个裁剪框，也需要重置掉裁剪目标的值，避免使用同一张图片无法触发watch
			pic.value = "";
			// 获取选取的文件
			const target = e.target as HTMLInputElement;
			const { files } = target;
			if (!files) return;
			const file: File = files[0];
			// 转换为base64传给裁切组件
			const reader: FileReader = new FileReader();
			reader.readAsDataURL(file);
			reader.onload = (): void => {
				// 更新裁切弹窗的图片源
				pic.value = String(reader.result);
				// 显示裁切弹窗
				isShowDialog.value = true;
				// 清空已选择的文件
				if (!uploadInput.value) return;
				uploadInput.value.value = "";
			};
		};
        const fileUpload = ()=>{
            uploadInput.value.click()
        }
		/**
		 * 获取裁切结果
		 */
		const getResult = async (): Promise<void> => {
			// console.log(cropper)
			// 获取生成的base64图片地址
			const base64: string = cropper.getDataURL();
			console.log(base64);
			// 把base64赋给结果展示区
			result.dataURL = base64;
            console.log('@@',result.dataURL)
			// 隐藏裁切弹窗
			isShowDialog.value = false;
            // 将base64传给父组件，方便后续将数据上传数据库
            emit('changeAvatar' , base64)
            // 上传图片
            request.post('updateImg' , {picture:result.dataURL}).then((res)=>{
                if(res.status == 0){
                    ElMessage({
                        type:'success',
                        message:'更新头像成功'
                    })
                }
            })
		};
		/**
		 * 重置默认的裁切区域
		 */
		const reset = (): void => {
			cropper.reset();
		};
		return {
			// 数据
			uploadInput,
			pic,
			result,
			isShowDialog,
			// 方法
			selectFile,
			getResult,
			reset,
            fileUpload,
		};
	},
};
</script>

<style lang='less' scoped>
@import "ant-design-vue/dist/antd.css";
.preview img {
	width: 100px;
	height: 100px;
}
.selectImg {
	opacity: 0;
}
.select{
    margin-top: 3%;
    .selectBtn{
        color: #fff;
        
    }
}
</style>